using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Build.Reporting;

public class APKBuild : Editor
{
    [MenuItem("Tool/APKBuild")]
    public static void Build()
    {
        BuildTarget buildTarget = BuildTarget.Android;
        BuildTargetGroup buildTargetGroup = BuildTargetGroup.Android;

        // 切换到 Android 平台
        EditorUserBuildSettings.SwitchActiveBuildTarget(buildTargetGroup, buildTarget);

        // keystore 路径, G:\keystore\one.keystore
        PlayerSettings.Android.keystoreName = "C:\\Program Files (x86)\\Jenkins\\workspace\\TestHeroDemo\\Assets\\user.keystore";
        // one.keystore 密码
        PlayerSettings.Android.keystorePass = "123456";
        // one.keystore 别名
        PlayerSettings.Android.keyaliasName = "bieming";
        // 别名密码
        PlayerSettings.Android.keyaliasPass = "123456";

        List<string> levels = new List<string>();
        foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
        {
            if (!scene.enabled) continue;
            // 获取有效的 Scene
            levels.Add(scene.path);
        }

        // 打包出 APK 名
        string apkName = string.Format("./{0}.apk", "Test");
        // 执行打包
        //BuildPipeline.BuildPlayer(levels.ToArray(), apkName, buildTarget, BuildOptions.None);

        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
        buildPlayerOptions.scenes = levels.ToArray();
        buildPlayerOptions.locationPathName = apkName;
        buildPlayerOptions.target = buildTarget;
        buildPlayerOptions.options = BuildOptions.None;
        BuildReport report = BuildPipeline.BuildPlayer(buildPlayerOptions);
        BuildSummary summary = report.summary;
        if (summary.result == BuildResult.Succeeded)
        {
            Debug.Log("Build succeeded: " + summary.totalSize + " bytes");
        }

        if (summary.result == BuildResult.Failed)
        {
            Debug.Log("Build failed");
        }


        AssetDatabase.Refresh();
    }
}
